using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api;
using Vin.Extension.Cache;
using Vin.Extension.Framework.Wechat.Options;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.Attributes;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Framework.Wechat.Service;

public class VinWxBaseService : VinBaseService
{
    private string WxTokenKey => $"wx:token:{WechatClient.Credentials.AppId}";

    public string WxAccessToken => GetToken().Result;
    
    [Inject] private IOptionsMonitor<WechatOption> _wechatOption = null!;
    
    protected WechatOption WechatOption => _wechatOption.CurrentValue;

    protected WechatApiClient WechatClient => new(_wechatOption.CurrentValue);

    /// <summary>
    /// 获取Token
    /// </summary>
    public async Task<string> GetToken()
    {
        var token = CacheFactory.GetCache<string>(WxTokenKey);
        if (!token.IsNullOrEmpty()) return token!;
        var res = await WechatClient.ExecuteCgibinTokenAsync(new());
        if (!res.IsSuccessful())
        {
            throw new BusinessException("获取wx-token失败");
        }

        CacheFactory.SetCache(WxTokenKey, res.AccessToken, new TimeSpan(0, 0, res.ExpiresIn - 200));
        return res.AccessToken;
    }
}